<template>
  <div v-show="userState.pageIndex === 1" class="codeLogin_container">
    <h3>
      <span v-if="userState.betaVersion">内测用户微信登录</span>
      <span v-if="!userState.betaVersion">微信登录</span>
    </h3>
    <div class="qrCode_login">
      <!-- <img v-if="qrCodeUrl" :src="qrCodeUrl" alt="微信登录二维码" /> -->
      <div id="loginContainer"></div>
    </div>
    <!-- <p>请打开微信扫一扫，扫描上方二维码</p> -->
    <div class="regist_findpass">
      <p>没有账号？<a href="javascript:;" @click="toRegist">立即注册</a></p>
      <p>忘记密码？<router-link tag="a">找回密码</router-link></p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import QRCode from 'qrcode' // 引入 QRCode 库
import { ElLoading, ElMessage } from 'element-plus';
import { useUserStore } from '../../store/user'
import { useRoute, useRouter } from 'vue-router'
import { getUserInfo } from '../../api/user';
//   import WxLogin from 'vue-wxlogin'

const { userState } = useUserStore()

const route = useRoute();
const router = useRouter()

const currentRoutePath = route.path
const queryParams = route.query

console.log('currentRoutePath:', currentRoutePath)

// 微信授权的 URL（包含你的 appid 和回调地址）
const appid = 'wx525eae2cf2928dd5' 
const redirectUri = 'https://www.gzrbxmt.com/api/wechat/callback' 
const encodedRedirectUri = encodeURIComponent('https://www.gzrbxmt.com/api/wechat/callback')// 替换为你自己的回调地址
console.log('redirectUri:::', redirectUri)
const scope = 'snsapi_login' // 微信授权范围
const state = 'my_random_state' // 防止 CSRF 攻击的随机参数

// const qrCodeText = `https://open.weixin.qq.com/connect/qrconnect?
//              appid=wx525eae2cf2928dd5
//              &redirect_uri=${encodedRedirectUri}
//              &response_type=code
//              &scope=snsapi_login
//              &state=my_random_state
//              #wechat_redirect`
             
const style = 'LmxvZ2luQ29udGFpbmVyIHsKICAgIHdpZHRoOiAxMDAlOwp9Cgoud2ViX3FyY29kZV9wYW5lbF9hcmVhIHsKICAgIHdpZHRoOiAyNzBweDsKfQoKLndycF9jb2RlIHsKICAgIHdpZHRoOiAyNTBweDsKfQoKLmxvZ2luUGFuZWwgLm5vcm1hbFBhbmVsIHsKICAgIGRpc3BsYXk6IGZsZXg7Cn0KCi5pbXBvd2VyQm94IC5xcmNvZGUgewogICAgd2lkdGg6IDI0MHB4OwogICAgaGVpZ2h0OiAyNDBweDsKfQoKLmltcG93ZXJCb3ggLnRpdGxlIHsKICAgIGRpc3BsYXk6IG5vbmU7Cn0KCi5pbXBvd2VyQm94IC5pbmZvIHsKICAgIHdpZHRoOiAyMDBweDsKfQoKLnN0YXR1c19pY29uIHsKICAgIGRpc3BsYXk6IG5vbmUKfQoKLmltcG93ZXJCb3ggLnN0YXR1cyB7CiAgICBwYWRkaW5nOiA3cHggMTRweCA3cHggMHB4OwogICAgdGV4dC1hbGlnbjogY2VudGVyOwp9CgouaW1wb3dlckJveCAucXJjb2RlIHsKICAgIGJvcmRlcjogbm9uZTsKICAgIG1hcmdpbi10b3A6IDZweDsKfQoKLmpzX3d4X2RlZmF1bHRfdGlwIHsKICAgIG1hcmdpbi10b3A6IDMwcHg7CiAgICBmb250LXNpemU6IDE2cHg7Cn0KCi5qc193eF9kZWZhdWx0X3RpcCBwIHsKICAgIGZvbnQtc2l6ZTogMTRweDsKfQ=='
function wechatLoginInit() {
  let obj = new WxLogin({
    self_redirect: true,
      id: 'loginContainer',
      appid,
      scope,
      state,
      style: 'white',
      // redirect_uri: redirectUri,
      redirect_uri: encodeURIComponent('https://www.gzrbxmt.com/wxCallback'),
      href: "data:text/css;base64," + style
  })
}

const messageHandler = (event) => {
  // 确保消息来自你信任的来源
  if (event.origin === 'https://www.gzrbxmt.com') {

  console.log('从iframe里发送回来的数据event：', event)

  if ( event.data === 'timeout' ) {
    ElMessage({
      message: '请求超时，请重新再试',
      type: 'error',
      duration: 5 * 1000
    })
    wechatLoginInit()
    return 
  }

  const data = event.data.data
  if (data.status && data.data && data.data.token) {
      // 已绑定
      if(data.data.token) {
        userState.token = data.data.token
        getUserInfo().then(res => {
          console.log('获取用户信息：', res)
          const userData = res.data.data
          if (res.status === 200) {
              userState.email = userData.email
              userState.username = userData.username
              userState.nickname = userData.nickname
              userState.tel = userData.tel
              userState.avatar = userData.avatar
              console.log('route.name:', route.name)
              if ( route.name.includes('AIMusic') ) {
                  location.reload()
                  userState.isShowLogin = false
              }
              ElMessage({
                message: '登录成功',
                type: 'success',
                duration: 5 * 1000
              })
              userState.isShowLogin = false
          }
        })
      }
    } else if(!data.status) {
      // 未绑定
      userState.uuid = data.wechatid
      if(data.wechatid) {
        userState.pageIndex = 3  // 显示绑定弹窗
      }
    }
  }
};

onMounted(() => {

  watch(() => userState.wechatLogin, (val)=> {
    if (val) {
      wechatLoginInit()
      userState.wechatLogin = false
    }
  })

  // 监听 iframe 发送的消息
  window.addEventListener('message', messageHandler);

})

// 在组件销毁时清除定时器
onBeforeUnmount(() => {

  // 清理事件监听器
  window.removeEventListener('message', messageHandler);
});

// 跳转到注册页面
function toRegist() {
  userState.pageIndex = 2
}
</script>

<style scoped>
.codeLogin_container {
  background: linear-gradient(180deg, rgba(161, 166, 190, 1) 0%, rgba(148, 129, 183, 1) 51.99999809265137%, rgba(174, 149, 250, 1) 100%);
  border-radius: 6px;
  width: 576px;
  height: 570px;
  padding: 50px 0;
  box-sizing: border-box;
  font-size: 14px;
  color: #FFF;
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: center;
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 11;
}

.codeLogin_container h3 {
  font-size: 18px;
}

.qrCode_login {
  width: 250px;
  height: 340px;
  box-sizing: border-box;
  margin: 40px auto 20px auto;
  border-radius: 10px;
  overflow: hidden;
}

.regist_findpass {
  width: 75%;
  height: 20px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  position: absolute;
  bottom: 50px;
}

.regist_findpass a {
  color: #7848f1;
}

</style>
